import fitz  # PyMuPDF
import os

def extract_images_from_pdf(pdf_path, output_folder):
    """
    从指定的 PDF 文件中提取所有图片，并保存到指定的输出文件夹。

    :param pdf_path: str - PDF 文件的路径。
    :param output_folder: str - 存储提取图片的目标文件夹。
    """
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    doc = fitz.open(pdf_path)

    for page_num in range(len(doc)):
        page = doc.load_page(page_num)
        image_list = page.get_images(full=True)

        for img_index, img in enumerate(image_list):
            xref = img[0]
            base_image = doc.extract_image(xref)
            image_bytes = base_image["image"]
            image_ext = base_image["ext"]

            # 构建图像文件名
            image_filename = f"page_{page_num + 1}_img_{img_index + 1}.{image_ext}"
            image_path = os.path.join(output_folder, image_filename)

            with open(image_path, "wb") as image_file:
                image_file.write(image_bytes)

    doc.close()

# 使用示例
pdf_file = "F:\\a513a7d4661347d9bcd97a722b9e8797.pdf"  # 替换为你的 PDF 文件路径
output_directory = "F:\\extracted_images"  # 替换为你想保存图片的目录
extract_images_from_pdf(pdf_file, output_directory)
